import Database from 'better-sqlite3';
import path from 'path';
import tables, { DB_VERSION } from './tables';
// import verifyDB from './verifyDB'
// import migrateData from './migrate'
import migrationManager from './migratesManager';

let db: Database.Database;

const initTables = (db: Database.Database) => {
  db.exec(`
    ${Array.from(tables.values()).join('\n')}
    INSERT INTO "main"."db_info" ("field_name", "field_value") VALUES ('version', '${DB_VERSION}');
    INSERT INTO "main"."user_info" ("id","name","password", "status") VALUES ('1', 'admin', '000000', 0);
  `);
};

// 打开、初始化数据库
export const init = (lxDataPath: string): boolean | null => {
  const databasePath = path.join(lxDataPath, 'video-annotion.data.db');
  let dbFileExists = true;

  try {
    db = new Database(databasePath, {
      fileMustExist: true,
      // verbose: process.env.NODE_ENV !== 'production' ? console.log : undefined,
    });
  } catch (error) {
    console.log(error);
    db = new Database(databasePath, {
      // verbose: process.env.NODE_ENV !== 'production' ? console.log : undefined,
    });
    initTables(db);
    dbFileExists = false;
  }

  // if (dbFileExists) migrateData(db)
  if (dbFileExists) migrationManager(db);

  // https://www.sqlite.org/pragma.html#pragma_optimize
  if (dbFileExists) db.exec('PRAGMA optimize;');
  // if (!verifyDB(db)) {
  //   db.close()
  //   return null
  // }

  // https://www.sqlite.org/lang_vacuum.html
  // db.exec('VACUUM "main"')

  process.on('exit', () => db.close());
  console.log('db inited');
  return dbFileExists;
};

// 获取数据库实例
export const getDB = (): Database.Database => db;
